import 'dart:convert';

import 'package:app_info/app_info.dart';
import 'package:app_info/info/appsflyer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:httpx/httpx.dart';
import 'package:native_flutter_proxy/native_proxy_reader.dart';
import 'package:smartloan_mdc/extension/extension.dart';
import 'package:smartloan_mdc/http/api/api.dart';
import 'package:smartloan_mdc/model/app_config_model.dart';
import 'package:smartloan_mdc/utils/auth/auth.dart';
import 'package:smartloan_mdc/utils/storage/get_storage.dart';
import 'package:sml_encrypt/encrypt/encrypt.dart';

import '../../http/http_base_config.dart';
import '../../http/interceptor/base_interceptor.dart';
import '../../route/app_routes.dart';
import '../../utils/locator/app_config.dart';
import '../../utils/locator/locator.dart';
import '../widgets/base_page.dart';

class SplashPage extends BasePage {
  const SplashPage({super.key});

  @override
  BasePageState<BasePage> getState() => _SplashPageState();
}

class _SplashPageState extends BasePageState<SplashPage> {

  @override
  String get pageName => 'splashPage';

  @override
  void initState() {
    initSync();
    super.initState();
  }

  @override
  Widget buildWidget() {
    return Center(
      child: "ic_launcher".appImg(width: 100.r, height: 100.r),
    );
  }

  initSync() async {
    await AppStorage().init();
    await AppsFlyer().afInit(locator<AppConfig>().getAppConfig().extraMeta!.afId ?? '');
    await AppInfo().appInfoInit();

    await SmlEncryptUtil().init(SmlEncryptUtil.generateKey(AppInfo().packageName));
    await httpInit();

    Future.delayed(3.seconds, () => checkAppConfig());
  }

  httpInit() async {
    // debugPrint('httpInit111');

    if (Httpx().httpBaseConfig != null) return;

    Httpx().init(AppHttpBaseConfig());
    Httpx().addInterceptors(iterable: [BaseInterceptor()]);

    ProxySetting settings = await NativeProxyReader.proxySetting;
    // debugPrint('setting host: ${settings.host} ${settings.port}');
    if (settings.host != null) {
      Httpx().setProxy(settings.host ?? '', settings.port ?? 0);
    }
  }

  checkActive() async {
    if ((AppStorage().readKey(StorageKey.activeDevice) ?? false) == false) {
      try {
        bool isSuccess = await RequestApi.activeDevice() as bool;
        AppStorage().writeKey(StorageKey.activeDevice, isSuccess);

      } on Exception catch (e) {
        // AppHttpBaseConfig().exceptionHandle(e);
      }
    }
  }

  checkAppConfig() async {
    final config = AppStorage().readKey(StorageKey.countryConfig) ?? {};
    debugPrint('checkAppConfig => $config');

    if (config.isNotEmpty) {

      await locator<AppConfig>().setModel(config);
      checkActive();
      checkLogin();

    } else {
      Get.offAndToNamed(AppRoutes.home,
        arguments: {'url': locator<AppConfig>().appConfigModel.baseUrl});
    }
  }

  checkLogin() async {
    if (Auth.isLogin()) {
      Get.offAndToNamed(AppRoutes.home, arguments: {
        'url': locator<AppConfig>().appConfigModel.baseUrl,
        // 'url': 'http://loanMarketApp.gccloud.xyz',
        'checkVersion': true
      });
    } else {
      Get.offAndToNamed(AppRoutes.phone);
    }
  }



}


